import { computed, ref, watchEffect } from 'vue';
import { RouteRecordRaw, RouteRecordNormalized } from 'vue-router';
import usePermission from '@/hooks/permission';
import { useAppStore, useMenusStore } from '@/store';
import appClientMenus from '@/router/app-menus';

export default function useMenuTree() {
  const permission = usePermission();
  const appStore = useAppStore();
  const menusStore = useMenusStore();
  const appRoute = computed(() => {
    if (appStore.menuFromServer) {
      return appStore.appAsyncMenus;
    }
    return appClientMenus;
  });

  if (menusStore.currMenus.length === 0) {
    let data = [
      {
        path: '/homepage',
        name: 'homepage',
        meta: {
          locale: '首页',
          hideInMenu: false,
          icon: '#',
        },
        children: [
          {
            menuId: 2,
            menuName: '工作台',
            parentId: 1,
            orderNum: 5,
            path: '/homepage/Workplace',
            isFrame: 1,
            menuType: 'M',
            visible: 1,
            status: 1,
            icon: 'icon-gongzuotai',
            remark: '系统管理目录',
            name: 'Workplace',
            meta: {
              locale: '工作台',
              hideInMenu: false,
              icon: 'icon-gongzuotai',
            },
            children: null,
          },
          {
            menuId: 8,
            menuName: '菜单管理',
            parentId: 1,
            path: '/homepage/MenuManagement',
            isFrame: 1,
            visible: 1,
            status: 1,
            icon: 'icon-shezhi',
            name: 'MenuManagement',
            meta: {
              locale: '菜单管理',
              hideInMenu: false,
              icon: 'icon-shezhi',
            },
            children: null,
          },
          {
            menuId: 2003,
            menuName: '系统设置',
            parentId: 1,
            orderNum: 1,
            path: '/homepage/SystemSettings',
            menuType: 'C',
            visible: 1,
            status: 1,
            icon: 'icon-xitongtongjifenxibaobiao',
            name: 'SystemSettings',
            meta: {
              locale: '系统设置',
              hideInMenu: false,
              icon: 'icon-xitongtongjifenxibaobiao',
            },
            children: [
              {
                menuId: 2004,
                menuName: '人员信息',
                parentId: 2003,
                orderNum: 1,
                path: '/homepage/SystemSettings/personnel-information',
                menuType: 'C',
                visible: 1,
                status: 1,
                node: null,
                name: 'personnel-information',
                meta: {
                  locale: '人员信息',
                  hideInMenu: false,
                },
                children: null,
              },
              {
                menuId: 2006,
                menuName: '岗位管理',
                parentId: 2003,
                orderNum: 1,
                path: '/homepage/SystemSettings/Post-Management',
                menuType: 'C',
                visible: 1,
                status: 1,
                node: null,
                name: 'Post-Management',
                meta: {
                  locale: '岗位管理',
                  hideInMenu: false,
                },
                children: null,
              },
              {
                menuId: 2007,
                menuName: '部门岗位',
                parentId: 2003,
                orderNum: 1,
                path: '/homepage/SystemSettings/organizational-structure',
                menuType: 'M',
                visible: 1,
                status: 1,
                node: null,
                name: 'organizational-structure',
                meta: {
                  locale: '部门岗位',
                  hideInMenu: false,
                },
                children: null,
              },
              {
                menuId: 2009,
                menuName: '角色与权限',
                parentId: 2003,
                orderNum: 1,
                path: '/homepage/SystemSettings/role-permission',
                menuType: 'C',
                visible: 1,
                status: 1,
                node: null,
                name: 'role-permission',
                meta: {
                  locale: '角色与权限',
                  hideInMenu: false,
                },
                children: null,
              },
              {
                menuId: 2128,
                menuName: '基础设置',
                parentId: 2003,
                orderNum: 1,
                path: '/homepage/SystemSettings/BaseSettings',
                isFrame: 1,
                menuType: 'C',
                visible: 1,
                status: 1,
                node: [
                  {
                    menuId: 2129,
                    menuName: '员工工号设置',
                    parentId: 2128,
                    orderNum: 1,
                    path: '/homepage/SystemSettings/BaseSettings/EmployeeNumber',
                    isFrame: 1,
                    menuType: 'C',
                    visible: 2,
                    status: 1,
                    node: null,
                    name: 'EmployeeNumber',
                    meta: {
                      locale: '员工工号设置',
                      hideInMenu: true,
                    },
                    children: null,
                  },
                ],
                name: 'BaseSettings',
                meta: {
                  locale: '基础设置',
                  hideInMenu: false,
                },
                children: [
                  {
                    menuId: 2129,
                    menuName: '员工工号设置',
                    parentId: 2128,
                    orderNum: 1,
                    path: '/homepage/SystemSettings/BaseSettings/EmployeeNumber',
                    isFrame: 1,
                    menuType: 'C',
                    visible: 2,
                    status: 1,
                    node: null,
                    name: 'EmployeeNumber',
                    meta: {
                      locale: '员工工号设置',
                      hideInMenu: true,
                    },
                    children: null,
                  },
                ],
              },
            ],
          },
        ],
      },
    ];
    menusStore.currMenus.push({ ...data });
  }

  let currChildren = ref(menusStore.currMenus[0].children); // 用来刷新menuTree中的computed的缓存

  const menuTree = computed(() => {
    // const copyRouter = JSON.parse(JSON.stringify(appRoute.value));

    // 获取pinia里面当前的路由，并取过滤一级路由，就是只需拿到二级路由显示在页面，所以要.children，并且currMenus数组只有一个对象，所以默认currMenus[0]就行了
    let copyRouter = ref();

    // if (window.name == "") {
    //   copyRouter.value = menusStore.currMenus[0].children;
    //   console.log("首次被加载");
    //   window.name = "isReload"; // 在首次进入页面时我们可以给window.name设置一个固定值
    // } else if (window.name == "isReload") {
    //   console.log("页面被刷新");
    // }
    // console.log(ref(JSON.parse(sessionStorage.getItem('currMenus') as any).children));
    currChildren.value = menusStore.currMenus[0].children; // 每次赋值刷新缓存，如果不刷新缓存则路由菜单不会变化

    if (sessionStorage.getItem('currMenus')) {
      copyRouter.value = JSON.parse(
        sessionStorage.getItem('currMenus') as any
      )[0].children;

      // menusStore.currMenus = JSON.parse(sessionStorage.getItem('currMenus') as any).children;
    } else {
      copyRouter.value = menusStore.currMenus[0].children;
    }
    // console.log(copyRouter.value);

    // copyRouter.sort((a: RouteRecordNormalized, b: RouteRecordNormalized) => {
    //   return (a.meta.order || 0) - (b.meta.order || 0);
    // });
    function travel(_routes: RouteRecordRaw[], layer: number) {
      if (!_routes) return null;

      const collector: any = _routes.map((element) => {
        // no access
        if (!permission.accessRouter(element)) {
          return null;
        }

        // leaf node
        if (element.meta?.hideChildrenInMenu || !element.children) {
          element.children = [];
          return element;
        }

        // route filter hideInMenu true
        element.children = element.children.filter(
          (x) => x.meta?.hideInMenu !== true
        );

        // Associated child node
        const subItem = travel(element.children, layer + 1);

        if (subItem.length) {
          element.children = subItem;
          return element;
        }
        // the else logic
        if (layer > 1) {
          element.children = subItem;
          return element;
        }

        if (element.meta?.hideInMenu === false) {
          return element;
        }

        return null;
      });
      return collector.filter(Boolean);
    }
    return travel(copyRouter.value as any, 0);
  });

  return {
    menuTree,
  };
}
